<template>
  <el-container>
    <el-aside width="300px" style="padding-top: 20px">
      <el-scrollbar>
        <el-card >
          <el-form :inline="true" :model="versionRef.queryForm" @keyup.enter="getVersionList()">
            <el-form-item>
              <el-input v-model="versionRef.queryForm.versionName" style="width: 150px" placeholder="版本名称" clearable ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="success" :icon="Search" circle @click="getVersionList()"/>
              <el-button type="primary" :icon="Plus" circle @click="addVersion()"/>
            </el-form-item>
          </el-form>
          <el-tree
              :data="versionRef.dataSource"
              :show-checkbox="false"
              node-key="id"
              default-expand-all
              :expand-on-click-node="false"
              style="left: -20px"
              @current-change="treeNodeChange"
          >
            <template #default="{ node, data }">
             <span class="custom-tree-node">
               <el-tooltip :content="node.label" placement="bottom">
                  <span style="max-width: 200px;display: inline-block;text-overflow: ellipsis;overflow: hidden;white-space: nowrap;">{{ node.label }}</span>
               </el-tooltip>
            <span>
             <el-button style="margin-left: 8px"  size="small" type="primary" :icon="Edit" circle @click="editVersion(node, data)"/>
             <el-button size="small" type="danger" :icon="Delete" circle @click="removeVersion(node, data)"/>
          </span>
        </span>
            </template>
          </el-tree>
        </el-card>
      </el-scrollbar>
    </el-aside>
    <el-main>
      <el-card>
        <el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
          <el-form-item>
            <el-input v-model="state.queryForm.templateName" placeholder="模板名称" clearable ></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="state.queryForm.groupCode" placeholder="模板分组" style="width: 100%" clearable>
              <el-option v-for="item in groupCodeList" :key="item.codeId" :label="item.codeName" :value="item.codeId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" @click="deleteBatchHandle()">删除</el-button>
            </el-form-item>
          <el-form-item>
            <el-button type="success" @click="copyTemplate()">复制模板</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="state.dataListLoading" :data="state.dataList" border style="width: 100%" @selection-change="selectionChangeHandle">
          <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
          <el-table-column prop="templateName" show-overflow-tooltip label="模板名称" header-align="center" align="center"></el-table-column>
          <el-table-column  label="模板标识" show-overflow-tooltip header-align="center" align="center">
            <template #default="scope">
              <el-tag effect="dark" type="success" > {{scope.row.templateType}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column  label="分组" show-overflow-tooltip header-align="center" align="center">
            <template #default="scope">
              <el-tag effect="dark" type="success" v-if="scope.row.groupCode ==1"> {{groupCodeFilter(scope.row)}}</el-tag>
              <el-tag effect="dark" type="warning" v-else> {{groupCodeFilter(scope.row)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="templateRoute" show-overflow-tooltip label="生成文件路径" header-align="center" align="center"></el-table-column>
          <el-table-column label="操作" fixed="right" header-align="center" align="center" width="230">
            <template #default="scope">
              <el-button type="primary" link @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button type="primary" link @click="editCodemirrirHandle(scope.row.id)">模板内容</el-button>
              <el-button type="primary" link @click="deleteBatchHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
            :current-page="state.page"
            :page-sizes="state.pageSizes"
            :page-size="state.limit"
            :total="state.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="sizeChangeHandle"
            @current-change="currentChangeHandle"
        >
        </el-pagination>

        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
        <!--代码编辑器-->
        <edit-codemirrir ref="editCodemirrirRef" @refreshDataList="getDataList"></edit-codemirrir>
      </el-card>
    </el-main>
    <el-dialog
        v-model="versionRef.visible"
        :title="!versionRef.dataForm.id ? '新增模版版本' : '修改模版版本'"
        width="30%"
    >
      <el-form-item label="版本名称" prop="author">
        <el-input v-model="versionRef.dataForm.versionName" placeholder="版本名称"></el-input>
      </el-form-item>
      <template #footer>
      <span class="dialog-footer">
        <el-button size="small" text @click="versionRef.visible = false">取消</el-button>
        <el-button size="small" type="primary" @click="submitVersion">确定</el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="selectVersionRef.visible"
        title="选择模板版本"
        width="30%"
    >
      <el-form-item label="版本名称" prop="author">

        <el-select v-model="selectVersionRef.dataForm.versionId" placeholder="请选择版本" style="width: 100%" clearable>
          <el-option v-for="item in versionRef.dataSource" :key="item.id" :label="item.label" :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <template #footer>
      <span class="dialog-footer">
        <el-button size="small" text @click="selectVersionRef.visible = false">取消</el-button>
        <el-button size="small" type="primary" @click="selectSubmitVersion">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup lang="ts">
import { reactive, ref,onMounted } from 'vue'
import { IHooksOptions } from '@/hooks/interface'
import { useCrud } from '@/hooks'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'
import EditCodemirrir from './edit-codemirror.vue'
import {Plus,Search,Edit,Delete} from '@element-plus/icons-vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import {templateVersionSubmitApi,templateVersionListApi,deleteTemplateVersionPageApi} from '@/api/templateVersion'
import {useCopyGeneratorApi} from '@/api/template'


const state: IHooksOptions = reactive({
	dataListUrl: '/gen/template/page',
	deleteUrl: '/gen/template',
	queryForm: {
    templateName: '',
		dbType: ''
	}
})
const versionRef = reactive({
  visible: false,
  dataForm:{
    id:'',
    versionName: ''
  },
  queryForm:{
    versionName: '',
    templateVersionId:undefined
  },
  dataSource:[]
})
const selectVersionRef= reactive({
  visible: false,
  dataForm:{
    versionId:''
  }
})
const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: number) => {
	addOrUpdateRef.value.init(id,state.queryForm.templateVersionId)
}

const editCodemirrirRef = ref()
const editCodemirrirHandle = (id?: number) => {
  editCodemirrirRef.value.init(id)
}
const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
//模板分组
const groupCodeList=[
  {
    codeId:1,
    codeName: '前端'
  },
  {
    codeId:2,
    codeName: '后端'
  }
]

const groupCodeFilter = (row) =>{
  const code =groupCodeList.filter(code => code.codeId == row.groupCode)
  if(code.length>0){
    return code[0].codeName
  }
}

//树形组件构建
interface Tree {
  id: number
  label: string
  children?: Tree[]
}
//添加模板版本
const addVersion= ()=>{
  versionRef.dataForm = {id:'',versionName:''}
  versionRef.visible = true
}
//编辑模板版本
const editVersion = (node: Node, data: Tree) => {
  versionRef.dataForm = {id:node.data.id,versionName:node.data.label}
  versionRef.visible = true
}
//删除模板版本
const removeVersion = (node: Node, data: Tree) => {
  ElMessageBox.confirm(
      '是否要删除该模板版本(同时会删除模板内容)?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        const ids =[node.data.id]
        deleteTemplateVersionPageApi(ids).then(() =>{
          getVersionList();
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          versionRef.visible = false
        })

      })
}
//复制模板
const copyTemplate= ()=>{
  if(!state.dataListSelections || state.dataListSelections.length <=0){
    ElMessage({
      type: 'warning',
      message: '请选择要复制的数据'
    })
    return
  }
  selectVersionRef.visible = true
}
//提交复制的模板
const selectSubmitVersion= ()=>{
  console.log(state.dataListSelections)
  useCopyGeneratorApi(selectVersionRef.dataForm.versionId,state.dataListSelections).then(() =>{
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    getDataList()
    selectVersionRef.visible = false

  })

}
//提交模板版本数据
const submitVersion = ()=>{
  templateVersionSubmitApi(versionRef.dataForm).then(() =>{
    getVersionList();
    ElMessage({
      type: 'success',
      message: '操作成功',
    })
    versionRef.visible = false
  })
}
//获取模版版本数据
const getVersionList = () =>{
  const parms = {versionName: versionRef.queryForm.versionName}
  templateVersionListApi(parms).then(res =>{
     const data=res.data
    const formData = data.map(val =>{
      return {id:val.id,label:val.versionName}
    })
    versionRef.dataSource = formData
  })
}
//树点击
const treeNodeChange =(data,node)=>{
  state.queryForm.templateVersionId = node.data.id
  getDataList()
}
onMounted(() => {
  getVersionList()
})
</script>
<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

</style>
